/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xui_lib.component.imageview.edit;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;

/**
 * 图片过滤处理
 *
 * @author xuexiang
 * @since 2019-10-28 9:59
 */
class FilterImageView extends Image {
    private OnImageChangedListener mOnImageChangedListener;
    //private int vWidth;
    private int vHeight;
    //private boolean changePixelMap;

    public FilterImageView(Context context) {
        super(context);
    }

    public FilterImageView(Context context, AttrSet attrSet) {
        super(context, attrSet);
    }

    public FilterImageView(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init();
    }

    private void init() {
        setLayoutRefreshedListener(new LayoutRefreshedListener() {
            @Override
            public void onRefreshed(Component component) {
                showLog(getWidth()+"======="+getHeight());
              //  if(!changePixelMap)
               // changeImaSize(com.getWidth());
            }
        });
    }
    HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 00011, "my");

    void showLog(String str) {
        HiLog.debug(label, "%{public}s", str);
    }

    private void changeImaSize(int width) {
        //vWidth = width;
       showLog(width+"==");
        Size size = getBitmap().getImageInfo().size;
        showLog((size.height / size.width)+"==");
        float scale = (float) size.width / size.height;
        vHeight = (int) (width * scale);
        PixelMap.InitializationOptions opt = new PixelMap.InitializationOptions();
        opt.size = new Size(width, vHeight);
        PixelMap pixelMap = PixelMap.create(getPixelMap(), opt);
        setPixelMap(pixelMap);
        //changePixelMap=true;
    }

    public void setOnImageChangedListener(OnImageChangedListener onImageChangedListener) {
        mOnImageChangedListener = onImageChangedListener;
    }

    interface OnImageChangedListener {
        void onBitmapLoaded(PixelMap sourceBitmap);
    }

    @Override
    public void setPixelMap(PixelMap pixelMap) {
        super.setPixelMap(pixelMap);
        if (mOnImageChangedListener != null) {
            mOnImageChangedListener.onBitmapLoaded(getBitmap());
        }
    }

    @Override
    public void setImageElement(Element element) {
        super.setImageElement(element);
        if (mOnImageChangedListener != null) {
            mOnImageChangedListener.onBitmapLoaded(getBitmap());
        }
    }

    @Override
    public void setPixelMap(int resId) {
        super.setPixelMap(resId);
        if (mOnImageChangedListener != null) {
            mOnImageChangedListener.onBitmapLoaded(getBitmap());
        }
    }

    public void setImageURI(Uri uri) {
        setImagePath(displayPic(getContext(), uri));
        if (mOnImageChangedListener != null) {
            mOnImageChangedListener.onBitmapLoaded(getBitmap());
        }
    }

    /**
     * 将图片地址转成 FileDescriptor
     *
     * @param context 上下文
     * @param ur 图片地址
     * @return 图片 FileDescriptor
     */
    public static FileDescriptor displayPic(Context context, Uri ur) {
        DataAbilityHelper helper = DataAbilityHelper.creator(context);
        try {
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, "" + ur.getLastPath());
            FileDescriptor filedesc = helper.openFile(uri, "r");
            return filedesc;
        } catch (DataAbilityRemoteException | FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置图片
     *
     * @param filedesc 图片
     */
    public void setImagePath(FileDescriptor filedesc) {
        ImageSource cacheImageSource = ImageSource.create(filedesc, null);
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        decodingOptions.editable = true;
        PixelMap pixelMap = cacheImageSource.createPixelmap(decodingOptions);
        setPixelMap(pixelMap);
    }

    PixelMap getBitmap() {
        if (getPixelMap() != null) {
            return getPixelMap();
        }
        return null;
    }
}
